<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-row class="bottomLine">
        <el-form-item label="应用:" label-width="40">
          <el-select v-model="queryParams.applicationCode" multiple placeholder="请选择应用">
            <el-option
              v-for="dict in applicationList"
              :key="dict.appCode"
              :label="dict.name"
              :value="dict.appCode"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row :gutter="10" class="bottomLine" v-show="queryParams.initQueryType==='event'">
        <el-form-item label="初始事件" prop="status">
          <el-popover
            placement="bottom-start"
            width="800"
            trigger="click"
          >
            <PanelSelect ref="panelSelect" @selected="selected" :eventObj="1"/>
            <el-input slot="reference" v-model="queryParams.initEvent.initTypeName" placeholder="点击选择事件" readonly
                      style="width: 200px;" suffix-icon="el-icon-arrow-down">
            </el-input>
          </el-popover>
          <el-link type="primary" :underline="false" style="padding-left:20px;" @click="addRule(queryParams.initEvent.initRuleTypes)">
            <i class="el-icon-plus"></i> <span class="innerContent">筛选</span>
          </el-link>
          <el-link type="primary" :underline="false" style="padding-left:20px;" @click="queryParams.initQueryType='attribute'" >
            <i class="el-icon-plus"></i> <span class="innerContent">切换为用户属性</span>
          </el-link>
          <el-row v-show="queryParams.initEvent.initRuleTypes.length>0">
            <el-form-item label="" style="display: block;padding-left:40px;" label-width="60px">
							<AndOrLine style="height: calc(100% - 10px);" v-show="queryParams.initEvent.initRuleTypes.length>1" v-model="queryParams.initEvent.initConditionRelation"></AndOrLine>
              <p style="margin: 0 0 10px;" v-for="(eventItem,index) in queryParams.initEvent.initRuleTypes">
                <el-select v-model="eventItem.eventType" style="width:120px;margin-right: 10px;"
                           @change="eventTypeChange(eventItem,index)" value-key="id">
                  <el-option
                    v-for="dict in eventTypeOptions"
                    :key="dict.id"
                    :label="dict.eventTypeName"
                    :value="dict"
                  />
                </el-select>
                <el-select v-model="eventItem.eventItem" style="width:120px;margin-right: 10px;"  value-key="id">
                  <el-option
                    v-for="dict in allEventItemListOpts[eventItem.eventType.id]"
                    :key="dict.id"
                    :label="dict.eventItemName"
                    :value="dict"
                  />
                </el-select>
                <el-select v-model="eventItem.eventItemExpression" style="width:120px;margin-right: 10px;">
                  <el-option
                    v-for="dict in  eventPropertysOptions[eventItem.eventItem.valueType]"
                    :key="dict.id"
                    :label="dict.eventItemExpression"
                    :value="dict.eventItemCode"
                  />
                </el-select>
                <el-input v-model="eventItem.value1Str" type="text" controls-position="right" style="width:100px"
                          v-show="eventItem.eventItemExpression!='between'"></el-input>
                <span v-show="eventItem.eventItemExpression=='between'">
                <el-input v-model="eventItem.value1Str" type="text" controls-position="right"
                          style="width:90px"></el-input>与
                <el-input v-model="eventItem.value2Str" type="text" controls-position="right"
                          style="width:90px"></el-input>之间
            </span>
                <el-link type="primary" :underline="false" style="padding-left:20px;font-size:18px"
                         @click="removeRule(queryParams.initRuleTypes,index)">
                  <i class="el-icon-remove"></i>
                </el-link>
              </p>

            </el-form-item>
          </el-row>
        </el-form-item>
      </el-row>
      <el-row :gutter="10" class="bottomLine" v-show="queryParams.initQueryType==='attribute'">
        <el-form-item label="初始时间" prop="status">
          <el-select v-model="queryParams.initUserAttribute" style="width:120px" value-key="id">
            <el-option
              v-for="dict in userAttributeOptions"
              :key="dict.id"
              :label="dict.attributeRemark"
              :value="dict"
            />
          </el-select>
          <el-link type="primary" :underline="false" style="padding-left:20px;" @click="queryParams.initQueryType='event'" >
            <i class="el-icon-plus"></i> <span class="innerContent">切换为事件</span>
          </el-link>
        </el-form-item>
      </el-row>
      <h3>营收事件</h3>
      <el-form-item prop="status" class="bottomLine" v-for="(queryItem,index) in queryParams.queryItems">
        <el-popover
          placement="bottom-start"
          width="800"
          trigger="click"
        >
          <PanelSelect ref="panelSelect" @selected="selected" :eventObj="queryItem"/>
          <el-input slot="reference" v-model="queryItem.incomeTypeName" placeholder="点击选择事件" readonly
                    style="width: 200px;" suffix-icon="el-icon-arrow-down">
          </el-input>
        </el-popover>
        的
        <el-select v-model="queryItem.incomeEventType" style="width:120px"  value-key="id">
          <el-option
            v-for="dict in allEventItemListOpts[queryItem.incomeEventId]"
            :key="dict.id"
            :label="dict.eventItemName"
            :value="dict"
          />
        </el-select>&nbsp;&nbsp;
        <el-input v-model="queryItem.profitValue" type="number" v-show="queryItem.profitFlag" style="width:160px" placeholder="填写利润比例"></el-input>
        <el-link type="primary" :underline="false" style="padding-left:20px;" @click="changeProfitFun(queryItem)">
          <i class="el-icon-plus"></i> <span class="innerContent">{{queryItem.profitText}}</span>
        </el-link>
        <el-link type="primary" :underline="false" style="padding-left:20px;" @click="addRule(queryItem.incomeRuleTypes)">
          <i class="el-icon-plus"></i> <span class="innerContent">筛选</span>
        </el-link>
        <el-row v-show="queryItem.incomeRuleTypes.length>0">
          <el-form-item label="" style="display: block;padding-left:80px;" label-width="60px">
						<AndOrLine style="height: calc(100% - 10px);" v-show="queryItem.incomeRuleTypes.length>1" v-model="queryItem.queryConditionRelation"></AndOrLine>
            <p v-for="(eventItem,index) in queryItem.incomeRuleTypes">
              <el-select v-model="eventItem.eventType" style="width:120px;margin-right: 10px;"
                         @change="eventTypeChange(eventItem,index)" value-key="id">
                <el-option
                  v-for="dict in eventTypeOptions"
                  :key="dict.id"
                  :label="dict.eventTypeName"
                  :value="dict"
                />
              </el-select>
              <el-select v-model="eventItem.eventItem" style="width:120px;margin-right: 10px;"  value-key="id">
                <el-option
                  v-for="dict in allEventItemListOpts[eventItem.eventType.id]"
                  :key="dict.id"
                  :label="dict.eventItemName"
                  :value="dict"
                />
              </el-select>
              <el-select v-model="eventItem.eventItemExpression" style="width:120px;margin-right: 10px;">
                <el-option
                  v-for="dict in  eventPropertysOptions[eventItem.eventItem.valueType]"
                  :key="dict.id"
                  :label="dict.eventItemExpression"
                  :value="dict.eventItemCode"
                />
              </el-select>
              <el-input v-model="eventItem.value1Str" type="text" controls-position="right" style="width:100px"
                        v-show="eventItem.eventItemExpression!='between'"></el-input>
              <span v-show="eventItem.eventItemExpression=='between'">
                <el-input v-model="eventItem.value1Str" type="text" controls-position="right"
                          style="width:90px"></el-input>与
                <el-input v-model="eventItem.value2Str" type="text" controls-position="right"
                          style="width:90px"></el-input>之间
            </span>
              <el-link type="primary" :underline="false" style="padding-left:20px;font-size:18px"
                       @click="removeRule(queryItem.incomeRuleTypes,index)">
                <i class="el-icon-remove"></i>
              </el-link>
            </p>

          </el-form-item>
        </el-row>
      </el-form-item>
      <div class="index_btns_3ZzaT bottomLine ">
          <span class="index_btn_3pwGp" @click="addIncomeRuleFun">
            <span class="index_btnIconNew_30w6G" >
              <i class="anticon">
                <svg width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false"
                     class=""><use xlink:href="#icon-new">
                  <svg id="icon-new" viewBox="0 0 1024 1024"><path
                    d="M512 102.4a409.6 409.6 0 1 1 0 819.2 409.6 409.6 0 0 1 0-819.2z m37.888 182.0672H474.112v189.5936H284.416v75.8784h189.5936v189.5936h75.8784v-189.5936h189.5936V474.0608h-189.5936V284.4672z"></path></svg>
                </use></svg></i></span><span>事件</span></span></div>
      <el-row v-show="queryParams.userAttributes.length>0">
        <el-form-item label="" style="display: block;padding-left:80px;" label-width="60px">
					<AndOrLine style="height: calc(100% - 10px);" v-show="queryParams.userAttributes.length>1" v-model="queryParams.userConditionRelation"></AndOrLine>
          <p v-for="(userAttr,index) in queryParams.userAttributes">
            <el-select v-model="userAttr.userAttribute" style="width:120px;margin-right: 10px;" value-key="id">
              <el-option
                v-for="dict in userAttributeOptions"
                :key="dict.id"
                :label="dict.attributeRemark"
                :value="dict"
              />
            </el-select>
            <el-select v-model="userAttr.valueExpression" style="width:120px;margin-right: 10px;">
              <el-option
                v-for="dict in eventPropertysOptions[userAttr.userAttribute.dataType]"
                :key="dict.eventItemCode"
                :label="dict.eventItemExpression"
                :value="dict.eventItemCode"
              />
            </el-select>
            <el-input v-model="userAttr.value1Str" type="text" controls-position="right" style="width:100px;margin-right: 10px;"
                      v-show="userAttr.valueExpression!='between'"></el-input>
            <span v-show="userAttr.valueExpression=='between'">
                <el-input v-model="userAttr.value1Str" type="text" controls-position="right"
                          style="width:90px"></el-input>与
                <el-input v-model="userAttr.value2Str" type="text" controls-position="right"
                          style="width:90px"></el-input>之间
            </span>
            <el-link type="primary" :underline="false" style="padding-left:20px;font-size:18px"
                     @click="removeRule(queryParams.userAttributes,index)">
              <i class="el-icon-remove"></i>
            </el-link>
          </p>

        </el-form-item>
      </el-row>
      <el-row class="bottomLine">
        <el-link type="primary" :underline="false" style="padding-left:20px;"  @click="addUserAttribute">
          <i class="el-icon-plus"></i> <span class="innerContent">用户筛选</span>
        </el-link>
      </el-row>
      <el-form-item label="按" prop="status" class="bottomLine">
        <el-tag
          :key="tag.eventType"
          v-for="tag in queryParams.groupTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{ tag.eventTypeName }}
        </el-tag>
        <el-select style="width:120px"
                   v-if="inputVisible"
                   v-model="inputValue"
                   ref="saveTagInput"
                   size="small"
                   value-key="id"
                   @keyup.enter.native="handleInputConfirm"
                   @change="handleInputConfirm">
          <el-option
            v-for="dict in eventTypeOptions"
            :key="dict.eventType"
            :label="dict.eventTypeName"
            :value="dict"
          />
        </el-select>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+</el-button>
        <el-link type="primary" :underline="false" style="padding-left:20px;">
          <i class="el-icon-setting"></i> <span class="innerContent">查看</span>
        </el-link>
      </el-form-item>
    </el-form>
    <el-container>

      <el-main>
        <el-row :gutter="10">
          <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-picture-outline" @click="queryDtaFun">趋势</el-button>
          </el-col>
          <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-share" @click="queryDtaFun">对比</el-button>
          </el-col>
          <el-col :span="5">
            <el-date-picker
              v-model="queryParams.dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              @change="queryDtaFun"
              range-separator="-"
              :picker-options="pickerOptions"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-col>


          <el-col :span="2" style="float: right">
            <el-checkbox v-model="queryParams.checked">预测视图</el-checkbox>
          </el-col>
        </el-row>
        <event-line-chart :chart-data="eventChartData" :chart-title="eventChartTitle" unit="%" :style="{width:'100%'}"/>
        <el-table
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border
          v-loading="loading"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column
            prop="date"
            label="指标"
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            prop="name"
            label="初始人数"
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            prop="address"
            label="LTV当天">
          </el-table-column>
          <el-table-column
            prop="address"
            label="LTV1">
          </el-table-column>
          <el-table-column
            prop="address"
            label="LTV2">
          </el-table-column>
          <el-table-column
            prop="address"
            label="LTV4">
          </el-table-column>
          <el-table-column
            prop="address"
            label="LTV5">
          </el-table-column>
        </el-table>
      </el-main>

    </el-container>
  </div>
</template>

<script>
import {getAllSiteFlowList, getKeepDataFun, getLTVQueryData} from "@/api/analytics/basemeasure";
import PanelSelect from "@/components/PanelSelect";
import EventLineChart from "@/views/report/ltv/comments/EventLineChart";
import AndOrLine from '@/components/AndOrLine/index.vue'
import {listApplication} from "@/api/config/application";
import {allEventItemsOptions, eventTypeOptions} from "@/api/config/item";
import {listAllPropertyResult} from "@/api/config/property";
import {getAllEventMethodResult} from "@/api/config/emethod";
import {getUserAttributeList} from "@/api/config/userattribute";
import {parseTime} from "@/utils/ruoyi";


export default {
  name: "ltv",
  components: {
    EventLineChart,
		PanelSelect,
		AndOrLine,
  },
  data() {
    return {
      switchValue: false,
      statusOptions: [],
      applicationList:[],
      params: {
        dateRange: ''
      },
      eventChartTitle:['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
      eventChartData: {
        name: 'Highest',
        type: 'line',
        smooth:false,
        data: [150, 230, 224, 218, 135, 147, 260]
      },
      // 遮罩层
      loading: false,
      tableData: [{
        id: 3,
        date: '$APP激活的启动时长',
        name: '368',
        address: '28.59',
        children: [{
          id: 31,
          date: '4-15 (四)',
          name: '368',
          address: '28.59%'
        }, {
          id: 32,
          date: '4-16 (五)',
          name: '286',
          address: '19.15%'
        }]
      }],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        initQueryType:'event',
        applicationCode:[],
        initUserAttribute: {},
        initEvent:{
          initTypeName:'',
          initEventType:'',
          initRuleTypes:[],
					initConditionRelation: 'and'
        },
        queryItems:[{
          incomeTypeName:'',
          incomeEventId:'',
          profitFlag:false,
          profitValue:'',
          profitText:'添加利润比例',
          incomeEventType:{},
          incomeRuleTypes:[],
					queryConditionRelation: 'and'
        }],
        userAttributes:[],
				userConditionRelation: 'and',
        groupTags:[],
        profitFlag:false,
        profitValue:undefined,
        dateRange:[parseTime(new Date(),'{y}-{m}-{d}'),parseTime(new Date(),'{y}-{m}-{d}')],
        name: undefined,
        status: undefined,
      },
      profitText:'添加利润比例',
      pickerOptions: {
        shortcuts: [{
          text: '今日',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '昨日',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            const day = start.getDay() || 7;
            var newStart = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 1 - day);
            picker.$emit('pick', [newStart, end]);
          }
        }, {
          text: '上周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      drawer: false,
      direction: 'rtl',
      formLabelWidth: '90px',
      index: 1,
      inputVisible: false,
      inputValue: '',
      ruleTypes3Flag: 0,
      eventTypeOptions: [],
      allEventItemListOpts:{},
      eventPropertysOptions:{},
      userAttributeOptions:[],
      referrerTypeOptions: [],
      // 表单参数
      form: {}
    };
  },
  created() {
    this.getApplicationList();
    this.getAllEventItemsList();
    this.getUserAttributeList();
    this.getEventTypeList();
    this.getAllFlowList();
  },
  methods: {
    getApplicationList() {
      listApplication({status: 'Y'}).then(response => {
        this.applicationList = response.rows;
        let that = this;
        this.applicationList.forEach(function (app) {
          if (app.defaultFlag === 'Y') {
            that.queryParams.applicationCode.push(app.appCode);
          }
        });
      });
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    getAllFlowList() {
      var param = {};
      getAllSiteFlowList(param).then(response => {
        this.lineChartData.actualData = response.data;
      });
    },
    selected(item,type) {
      if(type===1){
        this.queryParams.initEvent.initTypeName = item.eventTypeName;
        this.queryParams.initEvent.initEventType=item.eventType;
      }else{
        type.incomeTypeName=item.eventTypeName;
        type.incomeEventId=item.id;
      }
    },
    getEventTypeList() {
      var param = {status: 'Y'};
      eventTypeOptions(param).then(response => {
        this.eventTypeOptions = response.data;
      });
    },
    getAllEventItemsList(){
      allEventItemsOptions().then(response => {
        this.allEventItemListOpts = response.data;
      });
      listAllPropertyResult().then(response => {
        this.eventPropertysOptions = response.data;
      });
      getAllEventMethodResult().then(response => {
        this.allEventItemMethodOpts = response.data;
      });
    },
    getUserAttributeList() {
      var param = {status: 'Y'};
      getUserAttributeList(param).then(response => {
        this.userAttributeOptions = response.data;
      });
    },
    addRule(array){
      let eventItem={
        eventType:{},
        eventItem:{},
        eventItemExpression:'',
        valueType:'',
        value1Str:'',
        value2Str:'',
      };
      array.push(eventItem);
    },

    removeRule(array,index){
      array.splice(index,1);
    },
    eventTypeChange(array,index){
      array.eventItem={};
      array.eventItemExpression='';
      array.value1Str='';
      array.value2Str='';
    },
    addUserAttribute(){
      let userAttribute={
        userAttribute:{},
        valueExpression:'',
        dataType:'',
        valueType:'',
        value1Str:'',
        value2Str:'',
      };
      this.queryParams.userAttributes.push(userAttribute);
    },
    handleClose(tag) {
      this.queryParams.groupTags.splice(this.queryParams.groupTags.indexOf(tag.eventTypeName), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm(val) {
      if (val) {
        this.queryParams.groupTags.push(val);
      }
      console.log(this.queryParams.groupTags)
      this.inputVisible = false;
      this.inputValue = '';
    },

    queryDtaFun(){
      console.log(this.queryParams);
      this.loading=true;
      let requestJson=JSON.stringify(this.queryParams);
      getLTVQueryData({requestJson:requestJson}).then(response => {
        console.log(response.data);
        this.loading=false;
      });
    },
    changeProfitFun(queryItem){
      if(queryItem.profitFlag){
        queryItem.profitFlag=false;
        queryItem.profitValue=undefined;
        queryItem.profitText='添加利润比例';
      }else{
        queryItem.profitFlag=true;
        queryItem.profitText='取消利润比例';
      }
    },
    addIncomeRuleFun(){
      let queryItem={
        incomeTypeName:'',
				incomeEventId:'',
        profitFlag:false,
        profitValue:'',
        profitText:'添加利润比例',
        incomeEventType:{},
        incomeRuleTypes:[],
				queryConditionRelation: 'and'
      };
      this.queryParams.queryItems.push(queryItem)
    }
  }


};
</script>
<style lang="scss" scoped>
.innerContent {
  font-size: 14px;
  line-height: 20px;
  color: #307ef2;
  cursor: pointer;
}

.index_btns_3ZzaT .index_btn_3pwGp {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  margin-right: 20px;
}

.index_btns_3ZzaT .index_btnIconNew_30w6G {
  width: 20px;
  height: 20px;
  box-sizing: border-box;
  display: flex;
  align-self: center;
  justify-content: center;
  border: 3px solid #00bf8a;
  border-radius: 50%;
  margin-right: 8px;
}

.anticon {
  display: inline-block;
  color: inherit;
  font-style: normal;
  line-height: 0;
  text-align: center;
  text-transform: none;
  vertical-align: -.125em;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.index_btns_3ZzaT .index_btnIconNew_30w6G > i {
  display: flex;
  align-self: center;
  justify-content: center;
  font-size: 20px;
  color: #00bf8a;
}

.bottomLine {
  width: 100%;
  display: inline-block;
  border-bottom: 1px solid #e9f0f7;
  margin-bottom: 10px;
  padding-bottom: 10px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  font-size: 20px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 150px;
  margin-left: 10px;
  vertical-align: bottom;
}
// .app-container {
//   background-color: #f7f9fa;
// }
</style>
